<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="器具编码" prop="containerCode">
        <el-input
          v-model="queryParams.containerCode"
          placeholder="请输入器具编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="器具型号" prop="containerModelCode">
        <el-input
          v-model="queryParams.containerModelCode"
          placeholder="请输入器具型号编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="项目" prop="projectId">
        <el-select v-model="queryParams.projectId" placeholder="请选择项目" clearable>
          <el-option
            v-for="project in projectList"
            :key="project.projectId"
            :label="project.projectName"
            :value="project.projectId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="来源仓库" prop="sourceWarehouseId">
        <el-select v-model="queryParams.sourceWarehouseId" placeholder="请选择来源仓库" clearable>
          <el-option
            v-for="warehouse in warehouseList"
            :key="warehouse.warehouseId"
            :label="warehouse.warehouseName"
            :value="warehouse.warehouseId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="目标仓库" prop="targetWarehouseId">
        <el-select v-model="queryParams.targetWarehouseId" placeholder="请选择目标仓库" clearable>
          <el-option
            v-for="warehouse in warehouseList"
            :key="warehouse.warehouseId"
            :label="warehouse.warehouseName"
            :value="warehouse.warehouseId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="移库类型" prop="transferType">
        <el-select v-model="queryParams.transferType" placeholder="请选择移库类型" clearable>
          <el-option
            v-for="dict in dict.type.pack_transfer_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="移库阶段" prop="transferStage">
        <el-select v-model="queryParams.transferStage" placeholder="请选择移库阶段" clearable>
          <el-option
            v-for="dict in dict.type.pack_transfer_stage"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="生成方式" prop="autoGenerated">
        <el-select v-model="queryParams.autoGenerated" placeholder="请选择生成方式" clearable>
          <el-option
            v-for="dict in dict.type.pack_auto_generated"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="移库时间">
        <el-date-picker
          v-model="daterangeTransferTime"
          style="width: 240px"
          value-format="yyyy-MM-dd HH:mm:ss"
          type="datetimerange"
          range-separator="-"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['pack:transfer:add']"
        >手动移库</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['pack:transfer:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-s-data"
          size="mini"
          @click="handleStatistics"
          v-hasPermi="['pack:transfer:statistics']"
        >统计</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="transferList" @selection-change="handleSelectionChange">
      <el-table-column type="index" label="序号" width="60" />
      <el-table-column label="器具编码" align="left" prop="containerCode" width="100" :show-overflow-tooltip="true" />
      <el-table-column label="器具型号" align="center" prop="containerModelName" width="90" :show-overflow-tooltip="true" />
      <el-table-column label="项目名称" align="center" prop="projectName" width="120" :show-overflow-tooltip="true" />
      <el-table-column label="物料编码" align="center" prop="materialCode" width="100" :show-overflow-tooltip="true" />
      <el-table-column label="物料名称" align="center" prop="materialName" width="120" :show-overflow-tooltip="true" />
      <el-table-column label="来源仓库" align="center" prop="sourceWarehouseName" width="100" :show-overflow-tooltip="true" />
      <el-table-column label="目标仓库" align="center" prop="targetWarehouseName" width="100" :show-overflow-tooltip="true" />
      <el-table-column label="移库类型" align="center" prop="transferType" width="90">
        <template slot-scope="scope">
          <el-tag 
            :type="scope.row.transferType === '1' ? 'success' : 'info'"
            size="small">
            {{ transferTypeFormat(scope.row) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="移库阶段" align="center" prop="transferStage" width="90">
        <template slot-scope="scope">
          <el-tag 
            :type="scope.row.transferStage === '1' ? 'warning' : 'success'"
            size="small">
            {{ transferStageFormat(scope.row) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="生成方式" align="center" prop="autoGenerated" width="90">
        <template slot-scope="scope">
          <el-tag 
            :type="scope.row.autoGenerated === '1' ? 'success' : 'primary'"
            size="small">
            {{ autoGeneratedFormat(scope.row) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="移库时间" align="center" prop="transferTime" width="150">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.transferTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作员" align="center" prop="operatorName" width="80" :show-overflow-tooltip="true" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="80" fixed="right">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row)"
            v-hasPermi="['pack:transfer:query']"
          >详情</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加移库记录对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="器具编码" prop="containerId">
              <el-select v-model="form.containerId" placeholder="请选择器具" clearable filterable>
                <el-option
                  v-for="container in containerList"
                  :key="container.containerId"
                  :label="container.containerCode"
                  :value="container.containerId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="移库类型" prop="transferType">
              <el-select v-model="form.transferType" placeholder="请选择移库类型" @change="handleTransferTypeChange">
                <el-option
                  v-for="dict in dict.type.pack_transfer_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="移库阶段" prop="transferStage">
              <el-select v-model="form.transferStage" placeholder="请选择移库阶段">
                <el-option
                  v-for="dict in dict.type.pack_transfer_stage"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="来源仓库" prop="sourceWarehouseId">
              <el-select v-model="form.sourceWarehouseId" placeholder="请选择来源仓库" clearable>
                <el-option
                  v-for="warehouse in warehouseList"
                  :key="warehouse.warehouseId"
                  :label="warehouse.warehouseName"
                  :value="warehouse.warehouseId"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="目标仓库" prop="targetWarehouseId">
              <el-select v-model="form.targetWarehouseId" placeholder="请选择目标仓库">
                <el-option
                  v-for="warehouse in warehouseList"
                  :key="warehouse.warehouseId"
                  :label="warehouse.warehouseName"
                  :value="warehouse.warehouseId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="showMaterialFields">
            <el-form-item label="项目" prop="projectId">
              <el-select v-model="form.projectId" placeholder="请选择项目">
                <el-option
                  v-for="project in projectList"
                  :key="project.projectId"
                  :label="project.projectName"
                  :value="project.projectId"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="showMaterialFields">
          <el-col :span="12">
            <el-form-item label="物料编码" prop="materialCode">
              <el-input v-model="form.materialCode" placeholder="请输入物料编码" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="物料名称" prop="materialName">
              <el-input v-model="form.materialName" placeholder="请输入物料名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="showMaterialFields">
          <el-col :span="12">
            <el-form-item label="物料数量" prop="materialQuantity">
              <el-input v-model="form.materialQuantity" placeholder="请输入物料数量" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="内衬方案" prop="liningScheme">
              <el-input v-model="form.liningScheme" placeholder="例如：层板:5;垫块:20;" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" style="padding-left: 120px;">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 详情抽屉 -->
    <el-drawer
      title="移库记录详情"
      :visible.sync="detailOpen"
      size="600px"
      :close-on-click-modal="false"
      :wrapperClosable="false">
      <div style="padding: 20px;">
        <el-descriptions :column="1" border size="medium">
          <el-descriptions-item label="移库记录ID">{{ detailData.transferId }}</el-descriptions-item>
          <el-descriptions-item label="器具编码">{{ detailData.containerCode }}</el-descriptions-item>
          <el-descriptions-item label="器具型号">{{ detailData.containerModelName }}</el-descriptions-item>
          <el-descriptions-item label="项目名称">{{ detailData.projectName }}</el-descriptions-item>
          <el-descriptions-item label="物料编码">{{ detailData.materialCode }}</el-descriptions-item>
          <el-descriptions-item label="物料名称">{{ detailData.materialName }}</el-descriptions-item>
          <el-descriptions-item label="物料数量">{{ detailData.materialQuantity }}</el-descriptions-item>
          <el-descriptions-item label="内衬方案">{{ detailData.liningScheme }}</el-descriptions-item>
          <el-descriptions-item label="来源仓库">{{ detailData.sourceWarehouseName }}</el-descriptions-item>
          <el-descriptions-item label="目标仓库">{{ detailData.targetWarehouseName }}</el-descriptions-item>
          <el-descriptions-item label="移库类型">
            <el-tag :type="detailData.transferType === '1' ? 'success' : 'info'" size="small">
              {{ transferTypeFormat(detailData) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="移库阶段">
            <el-tag :type="detailData.transferStage === '1' ? 'warning' : 'success'" size="small">
              {{ transferStageFormat(detailData) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="生成方式">
            <el-tag :type="detailData.autoGenerated === '1' ? 'success' : 'primary'" size="small">
              {{ autoGeneratedFormat(detailData) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="移库时间">
            {{ parseTime(detailData.transferTime, '{y}-{m}-{d} {h}:{i}:{s}') }}
          </el-descriptions-item>
          <el-descriptions-item label="操作员">{{ detailData.operatorName }}</el-descriptions-item>
          <el-descriptions-item label="定位日志ID">{{ detailData.locationLogId }}</el-descriptions-item>
          <el-descriptions-item label="父移库记录ID">{{ detailData.parentTransferId }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">
            {{ parseTime(detailData.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}
          </el-descriptions-item>
          <el-descriptions-item label="备注">{{ detailData.remark }}</el-descriptions-item>
        </el-descriptions>
        
        <div class="drawer-footer">
          <el-button type="primary" @click="detailOpen = false">关 闭</el-button>
        </div>
      </div>
    </el-drawer>

    <!-- 统计对话框 -->
    <el-dialog title="移库统计信息" :visible.sync="statisticsOpen" width="600px" append-to-body>
      <el-row :gutter="20">
        <el-col :span="8">
          <div class="statistic-card">
            <div class="statistic-number">{{ statisticsData.totalTransfers || 0 }}</div>
            <div class="statistic-label">总移库次数</div>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="statistic-card">
            <div class="statistic-number">{{ statisticsData.fullTransfers || 0 }}</div>
            <div class="statistic-label">满箱移库</div>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="statistic-card">
            <div class="statistic-number">{{ statisticsData.emptyTransfers || 0 }}</div>
            <div class="statistic-label">空箱移库</div>
          </div>
        </el-col>
      </el-row>
      <el-row :gutter="20" style="margin-top: 20px;">
        <el-col :span="8">
          <div class="statistic-card">
            <div class="statistic-number">{{ statisticsData.autoTransfers || 0 }}</div>
            <div class="statistic-label">自动移库</div>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="statistic-card">
            <div class="statistic-number">{{ statisticsData.manualTransfers || 0 }}</div>
            <div class="statistic-label">手动移库</div>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="statistic-card">
            <div class="statistic-number">{{ (statisticsData.totalTransfers > 0 ? (statisticsData.autoTransfers / statisticsData.totalTransfers * 100).toFixed(1) : 0) }}%</div>
            <div class="statistic-label">自动化率</div>
          </div>
        </el-col>
      </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button @click="statisticsOpen = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listTransferRecord, getTransferRecord, addTransferRecord, exportTransferRecord, getTransferStatistics } from "@/api/pack/transfer";
import { listProject } from "@/api/pack/project";
import { listWarehouse } from "@/api/pack/warehouse";
import { listContainer } from "@/api/pack/container";

export default {
  name: "TransferRecord",
  dicts: ['pack_transfer_type', 'pack_transfer_stage', 'pack_auto_generated'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 移库记录表格数据
      transferList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示详情弹出层
      detailOpen: false,
      // 是否显示统计弹出层
      statisticsOpen: false,
      // 移库时间范围
      daterangeTransferTime: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        containerCode: null,
        containerModelCode: null,
        projectId: null,
        sourceWarehouseId: null,
        targetWarehouseId: null,
        transferType: null,
        transferStage: null,
        autoGenerated: null,
        startTime: null,
        endTime: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        containerId: [
          { required: true, message: "器具不能为空", trigger: "change" }
        ],
        transferType: [
          { required: true, message: "移库类型不能为空", trigger: "change" }
        ],
        transferStage: [
          { required: true, message: "移库阶段不能为空", trigger: "change" }
        ],
        targetWarehouseId: [
          { required: true, message: "目标仓库不能为空", trigger: "change" }
        ]
      },
      // 详情数据
      detailData: {},
      // 统计数据
      statisticsData: {},
      // 项目列表
      projectList: [],
      // 仓库列表
      warehouseList: [],
      // 器具列表
      containerList: [],
      // 是否显示物料字段
      showMaterialFields: false
    };
  },
  created() {
    this.getList();
    this.getProjectList();
    this.getWarehouseList();
    this.getContainerList();
  },
  methods: {
    /** 查询移库记录列表 */
    getList() {
      this.loading = true;
      if (null != this.daterangeTransferTime && '' != this.daterangeTransferTime) {
        this.queryParams.startTime = this.daterangeTransferTime[0];
        this.queryParams.endTime = this.daterangeTransferTime[1];
      } else {
        this.queryParams.startTime = null;
        this.queryParams.endTime = null;
      }
      listTransferRecord(this.queryParams).then(response => {
        this.transferList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 获取项目列表 */
    getProjectList() {
      listProject().then(response => {
        this.projectList = response.rows;
      });
    },
    /** 获取仓库列表 */
    getWarehouseList() {
      listWarehouse().then(response => {
        this.warehouseList = response.rows;
      });
    },
    /** 获取器具列表 */
    getContainerList() {
      listContainer().then(response => {
        this.containerList = response.rows;
      });
    },
    // 移库类型字典翻译
    transferTypeFormat(row, column) {
      return this.selectDictLabel(this.dict.type.pack_transfer_type, row.transferType);
    },
    // 移库阶段字典翻译
    transferStageFormat(row, column) {
      return this.selectDictLabel(this.dict.type.pack_transfer_stage, row.transferStage);
    },
    // 生成方式字典翻译
    autoGeneratedFormat(row, column) {
      return this.selectDictLabel(this.dict.type.pack_auto_generated, row.autoGenerated);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        transferId: null,
        containerId: null,
        projectId: null,
        materialCode: null,
        materialName: null,
        materialQuantity: null,
        liningScheme: null,
        sourceWarehouseId: null,
        targetWarehouseId: null,
        transferType: null,
        transferStage: null,
        remark: null
      };
      this.showMaterialFields = false;
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeTransferTime = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.transferId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "手动移库";
    },
    /** 查看详情按钮操作 */
    handleView(row) {
      const transferId = row.transferId;
      getTransferRecord(transferId).then(response => {
        this.detailData = response.data;
        this.detailOpen = true;
      });
    },
    /** 移库类型改变事件 */
    handleTransferTypeChange(value) {
      this.showMaterialFields = value === '1'; // 满箱移库时显示物料字段
      if (!this.showMaterialFields) {
        // 空箱移库时清空物料相关字段
        this.form.projectId = null;
        this.form.materialCode = null;
        this.form.materialName = null;
        this.form.materialQuantity = null;
        this.form.liningScheme = null;
      }
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          addTransferRecord(this.form).then(response => {
            this.$modal.msgSuccess("移库操作成功");
            this.open = false;
            this.getList();
          });
        }
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('pack/transfer/record/export', {
        ...this.queryParams
      }, `移库记录_${new Date().getTime()}.xlsx`)
    },
    /** 统计按钮操作 */
    handleStatistics() {
      getTransferStatistics(this.queryParams).then(response => {
        this.statisticsData = response.data;
        this.statisticsOpen = true;
      });
    }
  }
};
</script>

<style scoped>
.statistic-card {
  text-align: center;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e9ecef;
}

.statistic-number {
  font-size: 28px;
  font-weight: bold;
  color: #1890ff;
  margin-bottom: 8px;
}

.statistic-label {
  font-size: 14px;
  color: #666;
}

/* 表格文本样式优化 */
.el-table .cell {
  word-break: break-word;
  line-height: 1.4;
  max-height: 2.8em; /* 限制最大高度为2行 */
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2; /* 限制显示2行 */
  -webkit-box-orient: vertical;
}

/* 标签列的特殊处理 */
.el-table .cell .el-tag {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 100%;
  display: inline-block;
}

/* 抽屉样式 */
.drawer-footer {
  text-align: center;
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px solid #e8e8e8;
}

.el-drawer__header {
  margin-bottom: 20px;
  padding-bottom: 20px;
  border-bottom: 1px solid #e8e8e8;
}

.el-descriptions {
  margin-bottom: 20px;
}

.el-descriptions-item__label {
  width: 130px;
  font-weight: 600;
  color: #303133;
}
</style> 